var Log = require('../helper/logger');
var tagLogger = new Log.TagLogger('CMS-Wrap');
var _ = require('lodash');

let names = {
  front: Symbol('front'),
  end: Symbol('end'),
  post: Symbol('post'),
  spec: Symbol('spec'), //Vehicle spec Detail
  data: Symbol('data'), //运营位
  banner: Symbol('banner'), //运营位-banner
  news: Symbol('news'), //运营位-新闻快讯
  comment: Symbol('comment'), //运营位-大神车评
  topic: Symbol('topic'), //运营位-热门话题
  subject: Symbol('subject'), //运营位-新闻专题
  carBrand: Symbol('carBrand'), //爬虫-品牌
  carModel: Symbol('carModel'), //爬虫-型号
};
let middle = {
  [names.post]: {
    [names.front]: ['title', 'content', 'categoryId','carIds', 'authorId','editorId','channel','videoInfo'],
    [names.end]: ['title', 'content', 'categoryId','carIds', 'authorId','editorId','channel','videoInfo'],
  },
  [names.data]: {
    [names.front]: [
      'title',
      'subtitle',
      'img',
      'validateDate',
      'releateArticle',
    ],
    [names.end]: ['title', 'subtitle', 'img', 'validateDate', 'releateArticle'],
  },
  [names.banner]: {
    [names.front]: [
      'title',
      'subtitle',
      'img',
      'validateDate',
      'releateArticle',
    ],
    [names.end]: ['title', 'subtitle', 'img', 'validateDate', 'releateArticle'],
  },
  [names.news]: {
    [names.front]: ['title', 'validateDate', 'releateArticle'],
    [names.end]: ['title', 'validateDate', 'releateArticle'],
  },
  [names.comment]: {
    [names.front]: ['title', 'validateDate', 'releateArticle'],
    [names.end]: ['title', 'validateDate', 'releateArticle'],
  },
  [names.topic]: {
    [names.front]: ['title', 'img', 'validateDate', 'releateArticle'],
    [names.end]: ['title', 'img', 'validateDate', 'releateArticle'],
  },
  [names.subject]: {
    [names.front]: ['title', 'img', 'validateDate', 'releateArticle'],
    [names.end]: ['title', 'img', 'validateDate', 'releateArticle'],
  },
  [names.carModel]: {
    [names.front]: ['brandId', 'autohomeId', 'manufacturer', 'modelName'],
    [names.end]: ['brandId', 'autohomeId', 'manufacturer', 'modelName'],
  },
  [names.carBrand]: {
    [names.front]: ['capital', 'autohomeId', 'brandName', 'brandLogoUrl'],
    [names.end]: ['capital', 'autohomeId', 'brandName', 'brandLogoUrl'],
  },
  [names.spec]: {
    [names.front]: [
      'specName',
      'genre',
      'engine',
      'marketTime',
      'gearBox',
      'size',
      'bodyWork',
      'maxSpeed',
      'officialAcceleration',
      'measuredAcceleration',
      'measuredBraking',
      'measuredFuelConsumption',
      'fuelConsumption',
      'groundClearance',
      'qualityAssurance',
      'wheelbase',
      'frontTrack',
      'rearTrack',
      'miniGroundClearance',
      'allWeight',
      'tankVolume',
      'luggageVolume',
      'engineType',
      'displacementML',
      'displacementL',
      'inlet',
      'cylinderArrangement',
      'cylinderNum',
      'cylinderValves',
      'reductionRatio',
      'valveTrain',
      'bore',
      'pistonTravel',
      'maxHorsepower',
      'maxPower',
      'maxPowerspeed',
      'maxTorque',
      'maxTorquespeed',
      'engineSpecialtech',
      'fuelForm',
      'fuelMark',
      'fuelSupply',
      'cylinderHeadmaterial',
      'cylinderBlockmaterial',
      'environmentalStandard',
      'shiftNum',
      'gearboxType',
      'drivingMode',
      'fourwheelDrive',
      'centralDifferential',
      'frontSuspension',
      'rearSuspension',
      'powerType',
      'bodyStructure',
      'frontBrake',
      'rearBrake',
      'parkingType',
      'frontTire',
      'rearTire',
      'spareTire',
      'abs',
      'brakeDistribution',
      'brakeAssist',
      'tractionControl',
      'stabilityControl',
      'variableSuspension',
      'airSuspension',
      'electroSuspension',
      'variableSteeringratio',
      'frontDifferentiallock',
      'centralDifferentiallock',
      'rearDifferentiallock',
      'carId',
      'specImg'
    ],
    [names.end]: [
      'specName',
      'genre',
      'engine',
      'marketTime',
      'gearBox',
      'size',
      'bodyWork',
      'maxSpeed',
      'officialAcceleration',
      'measuredAcceleration',
      'measuredBraking',
      'measuredFuelConsumption',
      'fuelConsumption',
      'groundClearance',
      'qualityAssurance',
      'wheelbase',
      'frontTrack',
      'rearTrack',
      'miniGroundClearance',
      'allWeight',
      'tankVolume',
      'luggageVolume',
      'engineType',
      'displacementML',
      'displacementL',
      'inlet',
      'cylinderArrangement',
      'cylinderNum',
      'cylinderValves',
      'reductionRatio',
      'valveTrain',
      'bore',
      'pistonTravel',
      'maxHorsepower',
      'maxPower',
      'maxPowerspeed',
      'maxTorque',
      'maxTorquespeed',
      'engineSpecialtech',
      'fuelForm',
      'fuelMark',
      'fuelSupply',
      'cylinderHeadmaterial',
      'cylinderBlockmaterial',
      'environmentalStandard',
      'shiftNum',
      'gearboxType',
      'drivingMode',
      'fourwheelDrive',
      'centralDifferential',
      'frontSuspension',
      'rearSuspension',
      'powerType',
      'bodyStructure',
      'frontBrake',
      'rearBrake',
      'parkingType',
      'frontTire',
      'rearTire',
      'spareTire',
      'abs',
      'brakeDistribution',
      'brakeAssist',
      'tractionControl',
      'stabilityControl',
      'variableSuspension',
      'airSuspension',
      'electroSuspension',
      'variableSteeringratio',
      'frontDifferentiallock',
      'centralDifferentiallock',
      'rearDifferentiallock',
      'carId',
      'specImg'
    ],
  },
};

let verifyName = {
  video: Symbol('video'),
  audio: Symbol('audio'),
  audioAlbum: Symbol('audioAlbum'),
  star: Symbol('star'),
  live: Symbol('live'),
  pool: Symbol('pool'),
  front: Symbol('front'),
};
let verifyData = {
  [verifyName.video]: {
    nameCn: 'title',
    subTitle: 'subTitle',
    //'starring':'starring',
    //'picAll':'pic',
  },
  [verifyName.audio]: {
    name: 'title',
    subTitle: 'subTitle',
    //'artists':'starring',
  },
  [verifyName.audioAlbum]: {
    name: 'title',
    subTitle: 'subTitle',
    //'artists':'starring',
    //'picCollections':'pic',
  },
  [verifyName.star]: {
    name: 'title',
    //'postS1':'pic',
  },
  [verifyName.pool]: {channelName: 'title'},
  [verifyName.live]: {
    title: 'title',
  },
};

function change(data, use, from, to) {
  let result = {};
  _.forEach(data, function(value, key) {
    let index = middle[use][from].indexOf(key);
    if (index == -1) {
      //result[key] = value;
      //tagLogger.error(key+" is not exist in "+JSON.stringify(middle[use][from]));
    } else {
      result[middle[use][to][index]] = value;
    }
  });
  return result;
}

function changeData(data, use, from, to) {
  if (_.isArray(data)) {
    return data.map(x => change(x, use, from, to));
  }
  return change(data, use, from, to);
}

function changeUseDate(data, from) {
  let result = {};
  _.forEach(verifyData[from], function(value, key) {
    result[value] = data[key];
  });
  return result;
}

function wrapObject(fn, data) {
  if (_.isArray(data)) {
    _.forEach(data, function(item) {
      wrapSingle[fn](item);
    });
    return data;
  }
  wrapSingle[fn](data);
  return data;
}
function wrapCount(data) {
  if (!data || !data.length) {
    return null;
  }
  return data[0].total;
}
var wrapSingle = {
  [names.carHome]: wrapCalendarSingle,
};
function wrapCalendarSingleFull(result) {
  if (result.relatedVideo)
    result.relatedVideo = JSON.parse(result.relatedVideo);
  if (result.img) result.img = JSON.parse(result.img);
  if (result.star) result.star = _.values(JSON.parse(result.star)).join(',');
  return result;
}
function wrapCalendarSingle(result) {
  if (result.relatedVideo)
    result.relatedVideo = JSON.parse(result.relatedVideo);
  if (result.img) result.img = JSON.parse(result.img);
  if (result.star) result.star = JSON.parse(result.star);
  return result;
}
//function wrapItemSingleFull(result){
//if(result.productLineIdNames)result.productLineIdNames = _.values(JSON.parse(result.productLineIdNames)).join(',');
//if(result.img)result.img =  JSON.parse(result.img);
//if(result.star)result.star = _.values(JSON.parse(result.star)).join(',');
//if(result.updatedAt)result.updatedAt = formatDate(result.updatedAt);
//if(result.orders && result.orders == conf.maxOrder+1)result.orders = 0;
//return result;
//}
//function wrapItemSingle(result){
//if(result.productLineIdNames)result.productLineIdNames = JSON.parse(result.productLineIdNames);
//if(result.img)result.img =  JSON.parse(result.img);
//if(result.star)result.star = JSON.parse(result.star);
//if(result.updatedAt)result.updatedAt = formatDate(result.updatedAt);
//if(result.orders && result.orders == conf.maxOrder+1)result.orders = 0;
//return result;
//}
function formatDate(date) {
  let d = new Date(date);
  return (
    d.getFullYear() +
    '-' +
    zero(d.getMonth() + 1) +
    '-' +
    zero(d.getDate()) +
    ' ' +
    zero(d.getHours()) +
    ':' +
    zero(d.getMinutes()) +
    ':' +
    zero(d.getSeconds())
  );
}
function zero(data) {
  return ~~data < 10 ? '0' + data : data;
}
// function wrapFromArrayToTree(arr){
// 	let mainMap = new Map();
// 	for(let data of arr){
// 		let key = data.MenuId;
// 		if(mainMap.has(key)){
// 			let key2 = data.PageId;
// 			if(key2 && mainMap.get(key).child.has(key2) && data.PackId){
// 				mainMap.get(key).child.get(key2).child.push({'packId':data.PackId,'packName':data.PackName,'checked':data.checked});
// 			}else if(key2){
// 				mainMap.get(key).child.set(key2,{'pageName':data.PageName,child:data.PackId?[{'packId':data.PackId,'packName':data.PackName,'checked':data.checked}]:[]});
// 			}
// 		}else{
// 			let pageMap = new Map();
// 			if(data.PageId){
// 				pageMap.set(data.PageId,{'pageName':data.PageName,'child':data.PackId?[{'packId':data.PackId,'packName':data.PackName,'checked':data.checked}]:[]});
// 			}
// 			mainMap.set(key,{'menuName':data.MenuName,'child':pageMap});
// 		}
// 	}
// 	let result = strMapToArray(mainMap,0);
// 	return result;
// }

function wrapFromArrayToTree(arr) {
  let mainMap = new Map();
  for (let data of arr) {
    wrapSing(mainMap, data, 0);
  }
  let result = strMapToArray(mainMap, 0);
  return result;
}
function wrapSing(mainMap, data, i) {
  let keyArr = ['pageId', 'packId'],
    valueArr = ['pageName', 'packName'];
  let key = data[keyArr[i]];
  if (!key) {
    return;
  }
  if (mainMap.has(key)) {
    if (i < keyArr.length - 2) {
      let key2 = data[keyArr[i + 1]];
      wrapSing(mainMap.get(key).child, data, i + 1);
    } else {
      if (data[keyArr[i + 1]])
        mainMap.get(key).child.push({
          [keyArr[i + 1]]: data[keyArr[i + 1]],
          [valueArr[i + 1]]: data[valueArr[i + 1]],
          checked: data.checked,
        });
    }
  } else {
    if (i < keyArr.length - 2) {
      let pageMap = new Map();
      wrapSing(pageMap, data, i + 1);
      mainMap.set(key, {[valueArr[i]]: data[valueArr[i]], child: pageMap});
    } else {
      mainMap.set(key, {
        [valueArr[i]]: data[valueArr[i]],
        child: data[keyArr[i + 1]]
          ? [
              {
                [keyArr[i + 1]]: data[keyArr[i + 1]],
                [valueArr[i + 1]]: data[valueArr[i + 1]],
                checked: data.checked,
              },
            ]
          : [],
      });
    }
  }
}

function strMapToArray(strMap, i) {
  let arr = ['pageId'];
  if (_.isMap(strMap)) {
    let obj = [];
    for (let [k, v] of strMap) {
      let rs = {};
      rs[arr[i]] = k;
      _.forOwn(v, function(value, key) {
        if (key != 'child') {
          rs[key] = value;
        }
      });
      rs.child = strMapToArray(v.child, i + 1);
      obj.push(rs);
    }
    return obj;
  }
  return strMap;
}
module.exports = {
  changeData,
  names,
  changeUseDate,
  verifyName,
  wrapObject,
  wrapCount,
  wrapFromArrayToTree,
};
